<template>
   <div v-if="loading">加载中...</div>
   <div v-else>
  <div class="article-detail shadow" v-for="article in articles" :key="article?.id">
    <div class="article-detail-title">
      {{ article.title }}
    </div>
    <div class="article-detail-info">
      <span>发布时间：{{ article.publish_date }}</span>
      <span>作者：{{ article.author }}</span>
      <span>浏览量：{{ article.views_count }}</span>
      <span>收藏量：{{ currentCollectCount ?? article.collect_count }}</span>
    </div>
    <div class="article-detail-content" v-html="article.content"></div>

     <ArticleLike
    :articleId="article.id"
    @collect-updated="handleCollectUpdate"
  />
    <!-- 点赞区域 -->

  </div>
  <!--上一篇 下一篇-->
  <!-- 父组件模板 -->
<ArticlePrevNext
  :prev="prev"
  :next="next"
  @prev-click="handlePrevClick"
  @next-click="handleNextClick"
/>

  <!-- 评论区域 -->
  <ArticleComment :articleId="articleId"/>
   </div>
</template>
<script setup>
import ArticleComment from '@/components/articles/details/comments/ArticleComment.vue'
import ArticleLike from '@/components/articles/details/ArticleLike.vue'
import ArticlePrevNext from '@/components/articles/details/ArticlePrevNext.vue'

const router = useRouter()

const emit = defineEmits(['article-toc'])
const prev = ref(null)
const next = ref(null)
const loading = ref(true)
//通过axios获取文章数据/api/cms/articles/1/
const articles = ref([])
const props = defineProps({
  articleId: {
    type: Number,
    required: true,
  },
})
// 新增内部状态管理当前文章ID
const currentArticleId = ref(props.articleId)
const getArticles = async () => {
  try {
    const res = await axios.get(`/api/cms/articles/${currentArticleId.value}/`, {requiredAuth: false}) // 使用动态ID
    articles.value = Array.isArray(res.data) ? res.data : [res.data] // 保证始终是数组
     emit('article-toc', String(articles.value[0].toc_html))
    router.push({ name: 'article-detail', params: { articleId: currentArticleId.value }, query: { title: articles.value[0].title, } }) // 跳转到当前文章详情页
  } catch (error) {
    console.error('获取文章失败:', error)
    articles.value = [] // 失败时设为空数组
  }
  finally {
    loading.value = false // 加载完成
  }
}


prev.value = ref(null)
next.value =ref(null)
const getPrevAndNext = async () => {
  try {
    const res = await axios.get(
      `/api/cms/articles/${currentArticleId.value}/get_prev_next_article/`,{requiredAuth: false})
    prev.value = res.data.prev || null
    next.value = res.data.next || null
  } catch (error) {
    console.error('获取相邻文章失败:', error)
  }
}
const currentCollectCount = ref(null)
const handleCollectUpdate = (newCount) => {
  currentCollectCount.value = newCount;
}
// 新增相邻文章点击处理
const handlePrevClick = (prevArticle) => {
  router.push(`/article/${prevArticle.id}`) // 根据实际路由格式调整
}

const handleNextClick = (nextArticle) => {
  router.push(`/article/${nextArticle.id}`)
}
// 创建统一加载方法
const loadData = async () => {
  loading.value = true
  try {
    await Promise.all([getArticles(), getPrevAndNext()])
  } catch (error) {
    console.error('加载失败:', error)
  } finally {
    loading.value = false
  }
}
// 添加props变化监听
watch(() => props.articleId, (newVal) => {
  currentArticleId.value = newVal
  loadData()
  // 自动滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
})


onMounted(async () => {
  loadData()
})

onUnmounted(() => {
  console.log('组件销毁')
  // 组件销毁时清空数据
  articles.value = []
  prev.value = null
  next.value = null
})
</script>
<style scoped>
.article-detail {
  background: var(--article-detail-bg-color, #fff);
  padding: 15px;
  box-shadow: 0 1px 8px #a6a6a6;
  margin: 15px 0;
}

.article-detail-title {
  text-align: center;
  margin: 20px 0px;
  color: var(--article-detail-title-color, #ffffff);
  font-weight: 700;
  text-shadow: 0 0 8px var(--article-detail-info-border-color, #808080);
  font-size: 24px;
}

.article-detail-info {
  border: 1px dashed var(--article-detail-info-border-color, #808080);
  font-size: 13px;
  color: var(--article-detail-info-border-color, #808080);
  padding: 5px 0;
  font-family: SimSun;
  text-align: center;
  margin: 0 0 10px;
}

.article-detail-info span {
  margin: 0 5px;
}

.article-detail-content {
  padding: 10px 5px;
  color: var(--article-detail-text-color, #808080);
  line-height: 1.8;
}

</style>